<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/1/2
  Time: 9:24
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>添加销售出库</title>
    <jsp:include page="../headPage.jsp"></jsp:include>
</head>
<body>
<input type="hidden" id="entryPerson" name="entryPerson">
<div id="addModelTable_outDiv" style="height: 80%;width: 100%"></div>

<div class="modal fade" id="salePlanModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width: 60%;height: 50%">
        <div class="modal-content">
            <div class="panel panel-default">
				<div class="panel-heading">销售计划</div>
				<div class="panel-body">
					<form id="formSearch1" class="form-horizontal">
						<div class="form-group" style="margin-top: 15px">
							<label class="control-label col-sm-2" for="pickDate">客户名称:</label>
							<div class="col-sm-3">
								<input type="text" class="form-control" id="customerName" name="customerName" placeholder="请输入客户名称">
							</div>
							<label class="control-label col-sm-1" for="pickDate">品编:</label>
							<div class="col-sm-3">
								<input type="text" class="form-control" id="pNum" name="pNum" placeholder="请输入品编">
							</div>
							<div class="col-sm-2" align="right">
								<button type="button" style="width: 150px;" id="btn_query2" class="btn btn-primary">查询</button>
							</div>
						</div>
					</form>
				</div> 
			</div>

            <input id="customerId" hidden="hidden">
            <table id="td_salePlanTable"></table>
            <div id="bottomTableDiv" style="font-size: 14px;"></div>

            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="backPlan()" id="backOutLib">确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div>
</body>

<!--  初始化  页面加载时  -->
<script>

	function toastrStyle(){
		toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": false,
            "positionClass": "toast-top-center",
            "preventDuplicates": false,
            "onclick": null,
            "showDuration": "5000",
            "hideDuration": "1000",
            "timeOut&quot": "100000",
            "extendedTimeOut": "0",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "fadeIn",
            "hideMethod": "fadeOut"
        }; 
	}
	
    //页面加载时执行
    $(function (){
        comAjax("${pageContext.request.contextPath }/yzl/outLibNumLast.do","",function (data) {
            $('#entryPerson').val(data.staff.staffid);
        	initAddTable(data.returnNumber,"",data.staff.staffname,"",""/* ,"销售经理或副总经理或总经理" */,"");
        });
    })
    
    function removeTr(data){
    	$("#td_addModelTable tbody tr").eq(data).remove();
    	//得到修改的ID
    	var allTableData1 = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
        var allTableData = new Array();//获取表格的所有内容行
        if(allTableData1.length>0){
        	for(var i=0;i<allTableData1.length;i++){
                var count = $("#addTIndex"+allTableData1[i].pid).val();
                if(count!=undefined){
                	allTableData.push(allTableData1[i]);
                }
            }
        }
       for(var i=0;i<allTableData.length;i++){
            var count = $("#addTIndex"+allTableData[i].pid).val();
            allTableData[i].planQ = count;
            allTableData[i].amount = count*allTableData[i].remark8;
        }
       //得到原来的表头信息
       var objTable = dedaoValue("td_addModelTable");
       //更新第一层模态框的表格
       if (allTableData.length > 0) {
    	   initAddTable(objTable.number,objTable.time,objTable.entryPerson,objTable.customer,objTable.orderNumbers/* ,objTable.approvedMan */,"");
		} else {
			initAddTable(objTable.number,objTable.time,objTable.entryPerson,"",""/* ,objTable.approvedMan */,"");
		}
       for(var i=0;i<allTableData.length;i++){
       	   $('#td_addModelTable').bootstrapTable('insertRow', {
	           index:$('#td_addModelTable').bootstrapTable('getOptions').totalRows,
	           row:allTableData[i]
       		});
       }
    }

    //选择销售单
    function chosePlanNum(){
        initSalePlan();
    }

    //保存出库单
    function saveOutlib(){
        var entryPerson = $('#entryPerson').val();
    	//检验日期
        var addTime = $('#addTime').val();
        if (addTime=='') {
        	toastrStyle();
        	toastr.warning('请输入日期');
        	return false;
        }
        var d1=new Date(addTime);
        var nowDate = new Date();
        var d2 = new Date(nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + "-" + nowDate.getDate());
        if(d1<d2){
        	toastrStyle();
        	toastr.warning('出库日期不能小于当前日期');
        	return false;
        }
    	//得到原来的表格数据
        var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
        console.log(allTableData);
        //循环将填写的数量填入表格
        for(var i=0;i<allTableData.length;i++){
            var count = $("#addTIndex"+allTableData[i].pid).val();
            if(count == undefined){
                allTableData.splice(i,1);
            }else{
                allTableData[i].outQ = count;
                allTableData[i][0] = undefined;

            }

        }
        //得到选择的客户ID
        var customerId = $("#customerId").val();
        var obj = dedaoValue("td_addModelTable");
        console.log(obj);
        console.log(allTableData);
        var obj1 = {
            number : obj.number,
            customerId : customerId,
            planDate : obj.time,
            productors : allTableData,
            entryPerson : entryPerson
        };
        $("#save").attr("disabled",true);
        $.ajax({
            url : "${pageContext.request.contextPath }/yzl/addOutfrom.do",
            type : "POST",
            data : JSON.stringify(obj1),
            contentType: "application/json; charset=utf-8",
            dataType : "json",
            success : function(data){
                if(data == 1){
                	toastrStyle();
                    toastr.success("保存成功！");
                    setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
						//关闭模态框
						// 父页面刷新
                		backList();
					},2000);
                    //关闭当前窗口
                    //closeNow();
                    //$("#btn_save").attr("data-dismiss","modal");
                }else{
                	toastrStyle();
                	toastr.warning("保存失败！");
                }
            }
        })
        console.log("obj1----------------",obj1);
    }

    //关闭当前页面
    function closeNow(){
        var tab = parent.tab;
        tab.deleteTab(tab.getCurrentTabId());
    }

    //统一请求ajax
    function comAjax(url,data,fuc){
        $.ajax({
            type:"POST",
            url:url,
            data:data,
            success:function (data) {
                fuc(data);
            },
        })
    }

    //移出一行数据
    function remove(ele){
        $($(ele).parent()[0]).parent()[0].remove();
    }

    $('#btn_query2').on('click', function() {
		$('#td_salePlanTable').bootstrapTable('refresh', '${pageContext.request.contextPath }/yzl/cusOrderList.do');
	})
    
    //选择销售订单
    function backPlan(){
        //得到选择的数据
        var rows = $('#td_salePlanTable').bootstrapTable('getSelections');
        //var rows2 = $('#td_salePlanXQTable').bootstrapTable('getSelections');
        var allTableData = new Array();
        for(var j=0;j<rows.length;j++){
        	if (rows[j].productStock <= 0) {
        		toastrStyle();
            	toastr.warning("请选择存在库存的计划单！");
            	return false;
			} else {
				if (rows[j].productStock <= rows[j].lastPlanQ) {
					rows[j].lastPlanQ = rows[j].productStock;
					allTableData.push(rows[j]);
				} else {
					allTableData.push(rows[j]);
				}
			}
        }
        console.log(allTableData);
        var customerNames = "";
        var customerIds = "";
        var orderNumbers = "";
        for (var i = 0; i < allTableData.length; i++) {
			if (customerNames.indexOf(allTableData[i].customerName) == -1) {
				customerNames = customerNames+","+allTableData[i].customerName;
			}
			if (customerIds.indexOf(allTableData[i].customerId) == -1) {
				customerIds = customerIds+","+allTableData[i].customerId;
			}
			if (orderNumbers.indexOf(allTableData[i].orderNumber) == -1) {
				orderNumbers = orderNumbers+","+allTableData[i].orderNumber;
			}
		}
        var customerId = customerIds.substring(1, customerIds.length);
        //将客户ID 赋值
        if (customerId.indexOf(",") !=-1) {
        	toastrStyle();
        	toastr.warning("只能选择相同客户下的计划单！");
        	return false;
		} else {
			$("#customerId").val(customerId);
			//得到原来的表格数据
	        var objTable = dedaoValue("td_addModelTable");
	        //var allTableData = $('#td_addModelTable').bootstrapTable('getData');//获取表格的所有内容行
	        if(rows){
	            $("#salePlanModel").modal('hide');
	            initAddTable(objTable.number,objTable.time,objTable.entryPerson,customerNames.substring(1, customerNames.length-1),orderNumbers.substring(1, orderNumbers.length-1)/* ,objTable.approvedMan */,rows[0].id);
	            for(var i=0;i<allTableData.length;i++){
	                //for(var x = 0;x<rows.length;x++){
	                    //if(rows[x].id != allTableData[i].id){
	                        $('#td_addModelTable').bootstrapTable('insertRow', {
	                            index:$('#td_addModelTable').bootstrapTable('getOptions').totalRows,
	                            row:allTableData[i]
	                        });
	                    //}
	                //}
	            }
	        }else{
	        	toastrStyle();
	        	toastr.warning("请选择客户");
	        }
		}
    }
</script>


<!--      表格初始化       -->
<script>

    //返回list页面
    function backList(){
        window.location.href = "${pageContext.request.contextPath}/pages/yzlERP/outLibrary/salesOutLibrary.jsp";
    }

    //初始化添加表单
    function initAddTable(number,time,entryPerson,customer,beforeNumber/* ,approvedMan */,id){

        var $addModelTable_outDiv = $("#addModelTable_outDiv");
        if($addModelTable_outDiv.find("table").length > 0){
            $addModelTable_outDiv.empty();
        }
        var table = '<table id="td_addModelTable"></table>'
        $addModelTable_outDiv.append(table);

        if(beforeNumber == "" || beforeNumber == null){
            beforeNumber = '<a href="#" onclick="chosePlanNum()">选择销售计划单号</a>'
        }else{
            beforeNumber = '<a href="#" onclick="chosePlanNum()">'+beforeNumber+'</a>'
        }

        $addModelTable_outDiv.append(table);

        var listH = '<div class="modal-footer">\n' +
            '        <button type="button" class="btn btn-default" onclick="backList()">返回列表页面</button>\n' +
            '    </div>'
        $addModelTable_outDiv.append(listH);

        var div = '<div class="modal-footer">\n' +
            //'                    <button type="button" class="btn btn-default" onclick="closeNow()">关闭</button>\n' +
            '                    <button type="button" id="save" class="btn btn-primary" onclick="saveOutlib()">保存</button>\n' +
            '                </div>';
        $addModelTable_outDiv.append(div);

        if(time == "" || time == null){
            time = '<input type="text" name="addTime" id="addTime"\n' +
                '                               placeholder="yyyy-mm-dd"\n' +
                '                               class="form_datetime form-control"\n' +
                '                               >'
        }else{
            time = '<input type="text" name="addTime" id="addTime"\n' +
                '                               placeholder='+time+'\n' +
                '                               class="form_datetime form-control"\n' +
                '                               value="'+time+'">'
        }

        $('#td_addModelTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            toolbar: '#toolbarIn',
            //url:"${pageContext.request.contextPath }/yzl/customerOrderXq.do?id="+id,
            columns:[
                [
                    /* {
                        field : id,
                        valign: 'middle',
                        hidden:true,
                        align: "center",
                    }, */
                    {
                        field: 'name',
                        title: "出库单号",
                        valign:"middle",
                        align:"center",
                        colspan: 1
                    },
                    {
                        title: number,
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: "出库日期",
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: time,
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: "销售计划单号",
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {

                        title: beforeNumber,
                        valign:"middle",
                        field: 'aa',
                        align:"center",
                        colspan: 1,
                    }
                    
                ],
                [
                    /* {
                        field : id,
                        valign: 'middle',
                        hidden:true,
                        align: "center",
                    }, */
                    {
                        field: 'name',
                        title: "客户",
                        valign:"middle",
                        align:"center",
                        colspan: 1
                    },
                    {
                        title: customer,
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
					    title: "制单人",
					    valign:"middle",
					    align:"center",
					    colspan: 1,
					},
					{
					    title: entryPerson,
					    valign:"middle",
					    align:"center",
					    colspan: 3,
					},
					/* {
                        title: "审批人",
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    },
                    {
                        title: approvedMan,
                        valign:"middle",
                        align:"center",
                        colspan: 1,
                    } */
                ],
                [
                    {   field : id,
                        title: '序号',//标题  可不加
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                            return index+1;
                        }
                    },
                    {
                        field: 'carType',
                        title: '车种',
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                            return row.cartype;
                        }
                    },
                    {
                        field: 'carNumber',
                        title: '品编',
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                            return row.carNumber;
                        }
                    },
                    {
                        field: 'carName',
                        title: '品名',
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                            return row.carName;
                        }
                    },
                    /* {
                        field: 'batchNumber',
                        title: '批号',
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                                return "123456";
                        }
                    }, */
                    {
                        field: 'outQ',
                        title: '出库数量',
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                            return '<input type="number" min="0" oninput="comparedPlan(this,'+row.lastPlanQ+','+row.productStock+')" class="form-control" value="'+(row.lastPlanQ-row.outQ)+'" id="addTIndex'+row.pid+'"><input value="'+row.planQ+'" hidden="hidden">'
                        }
                    },/* ,
                    {
                        field: 'barderNumber',
                        title: '条码',
                        valign:"middle",
                        align:"center",
                        formatter: function (value, row, index) {
                        	return "123456";
                        }
                    } *//* ,
                    {
                        field: 'caozuo',
                        title: '操作',
                        valign:"middle",
                        align:"center"
                        formatter: function (value, row, index) {
                            return '<button type="button" class="btn btn-primary" id="'+index+'" onclick="delPro(this)">移除该产品</button>'
                        }
                    } */
                    {
                        field: 'remove',
                        title: '移除该产品',
                        valign: "middle",
                        align: "center",
                        formatter: function (value, row, index) {
                        	return '<button type="button" onclick="removeTr('+index+')" class="btn btn-primary">移除该产品</button>'
                        }
                    }
                ]
            ]
        });
        
        $(function () {
    		$(".form_datetime").datetimepicker({
    		 format: "yyyy-mm-dd",
    		 autoclose: true,
    		 todayBtn: true,
    		 todayHighlight: true,
    		 showMeridian: true,
    		 pickerPosition: "bottom-center",
    		 language: 'zh-CN',//中文，需要引用zh-CN.js包
    		 startView: 2,//月视图
    		 minView: 2//日期时间选择器所能够提供的最精确的时间选择视图
    		 });
    	 });
        var allRows = $("#tb_departments").bootstrapTable("getData");
        $('#myModal').modal({
            keyboard: true,
        })
        $('#toolbarIn').css("display","block");
    }

    function delPro(e) {
		//alert(e.id);
		remove(e);
	}
    
    function comparedPlan(data,planQ,productStock){
    	var num=data.value;
    	var maxNum = productStock>planQ?planQ:productStock;
    	if(num>maxNum){
    		toastrStyle();
    		toastr.warning('出库数量不能大于未出库数量或库存');
    		$('#'+data.id).val(maxNum);
    	}
    	var reg=/^[1-9]\d*$|^0$/;
    	/* if(data.value==''){
    		$('#'+data.id).val(1);
    	} */
    	if(!reg.test(data.value)){
    		toastrStyle();
    		toastr.warning('只能输入正整数');
    		var num=data.value.split('.')[0];
    		$('#'+data.id).val(num);
    	}
    }
    
    //初始化销售计划单
    function initSalePlan(){
        $('#td_salePlanTable').bootstrapTable({
            dataType: "json",
            method: 'post',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            clickToSelect: true,
            pagination: true,                   //是否显示分页（*）
            queryParams : function (params) {
                //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                var temp = {
                    limit: params.limit,                         //页面大小
                    offset: (params.offset / params.limit) + 1,   //页码
                    customerName : $('#customerName').val(),
                    pNum : $('#pNum').val()
                };
                return temp;
            },
            //singleSelect : true, // 单选checkbox
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10,20,30],        //可供选择的每页的行数（*）
            url:"${pageContext.request.contextPath }/yzl/cusOrderList.do",
            columns: [
                [
                    {
                        checkbox: true
                    },
                    {
                        field: 'orderNumber',
                        title: '计划单号'
                    },
                    {
                        field: 'customerName',
                        title: '客户'
                    },
                    {
                        field: 'cartype',
                        title: '车种'
                    },
                    {
                        field: 'carNumber',
                        title: '品编'
                    },
                    {
                        field: 'carName',
                        title: '品名'
                    },
                    {
                        field: 'lastPlanQ',
                        title: '未出库数量'
                    },
                    {
                        field: 'productStock',
                        title: '库存'
                    }]
            ]
        });
        $('#salePlanModel').modal({
            keyboard: true,
        })
      //行点击事件
        //$('#td_salePlanTable').on('click-row.bs.table', function (e, row, element) {initBottomTable(row.id);});
    }

  //底部详情列表初始化
    /* function initBottomTable(id){
        var $bottomTableDiv = $("#bottomTableDiv");
        if($bottomTableDiv.find("table").length > 0){
            url = "${pageContext.request.contextPath }/yzl/addCusOrderXq.do?id="+id;
            $("#td_salePlanXQTable").bootstrapTable('refresh', {url: url});
            //$bottomTableDiv.empty();
        }else{
            var table = '<table id="td_salePlanXQTable" style="font-size: 14px;"></table>'
            $bottomTableDiv.append(table);
        }

        $('#td_salePlanXQTable').bootstrapTable({
            dataType: "json",
            method: 'get',
            contentType: "application/x-www-form-urlencoded",
            cache: false,
            clickToSelect: true,
            toolbar: '#toolbarIn',
            url: "${pageContext.request.contextPath }/yzl/addCusOrderXq.do?id="+id,
            height:300,
            columns: [
                [
					{
				    	checkbox: true
					},
				    {
				        field: 'cartype',
				        title: '车种',
				        valign: "middle",
				        align: "center"
				    },
				    {
				        field: 'num',
				        title: '品编',
				        valign: "middle",
				        align: "center"
				    },
				    {
				        field: 'name',
				        title: '品名',
				        valign: "middle",
				        align: "center"
				    },
				    {
				        field: 'num',
				        title: '未出库数量',
				        valign: "middle",
				        align: "center",
				        formatter: function (value, row, index) {
                           return row.planQ-row.outQ;
                        }
				    }
                ]
            ]
        });
    } */
    
    //根据传入的表格ID 查询数据
    function dedaoValue(tableId){

        //拿到原来表格中填写的订单号和时间
        var $thead  = $($($("#"+tableId)[0]).find("thead")[0]);
        //拿到第一行
        var $tr1 = $($thead.find("tr")[0]);
        //拿到订单号
        var number = $($($tr1.find("th")[1]).find("div")[0]).text();
        //拿到时间
        var time = $("#addTime").val();
        //拿到计划单号
        var orderNumbers = $($($tr1.find("th")[5]).find("div")[0]).text();


        //拿到第二行
        var $tr2 = $($thead.find("tr")[1]);
        //拿到客户名称
        var customer = $($($tr2.find("th")[1]).find("div")[0]).text();
        console.log("customer--",customer);
		//拿到指定人
        var entryPerson = $($($tr2.find("th")[3]).find("div")[0]).text();
        //拿到审批人
        /* var approvedMan = $($($tr2.find("th")[5]).find("div")[0]).text(); */
        
        /* //拿到第三行
        var $tr3 = $($thead.find("tr")[2]);
        //拿到指定人
        var entryPerson = $($($tr3.find("th")[1]).find("div")[0]).text();
        //拿到审批人
        var approvedMan = $($($tr3.find("th")[3]).find("div")[0]).text(); */
        var obj = {
            number : number,
            time : time,
            customer : customer,
            entryPerson : entryPerson,
            /* approvedMan : approvedMan, */
            orderNumbers : orderNumbers
        };
        return obj;
    }
</script>

<!--    时间插件    -->

<script>
    layui.use(['form', 'layedit', 'laydate'], function() {
        var form = layui.form(),
            layer = layui.layer,
            layedit = layui.layedit,
            laydate = layui.laydate;

        //创建一个编辑器
        var editIndex = layedit.build('LAY_demo_editor');
        //自定义验证规则
        form.verify({
            title: function(value) {
                if(value.length < 5) {
                    return '标题至少得5个字符啊';
                }
            },
            pass: [/(.+){6,12}$/, '密码必须6到12位'],
            content: function(value) {
                layedit.sync(editIndex);
            }
        });

        //监听提交
        form.on('submit(demo1)', function(data) {
            layer.alert(JSON.stringify(data.field), {
                title: '最终的提交信息'
            })
            return false;
        });
    });
</script>

</html>
